// v2_jwt/handlers/middleware.go
package handlers

import (
	"context"
	"grpc-jwt-yonghurenzheng/v2.1_jwt/config"
	"grpc-jwt-yonghurenzheng/v2.1_jwt/models"
	"net/http"

	"strings"

	"github.com/golang-jwt/jwt/v4"
)

// JWTMiddleware 验证 JWT
func JWTMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 从请求头获取 token
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			writeJSONError(w, http.StatusUnauthorized, "请求头缺少 Authorization")
			return
		}

		// Token 格式为 "Bearer <token>"
		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			writeJSONError(w, http.StatusUnauthorized, "Authorization 请求头格式错误")
			return
		}
		tokenString := parts[1]

		// 解析 token
		claims := &models.Claims{}
		token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
			return config.JWTKey, nil
		})

		if err != nil || !token.Valid {
			writeJSONError(w, http.StatusUnauthorized, "无效的 Token")
			return
		}

		// 将用户信息存入 request context，方便后续 handler 使用
		ctx := context.WithValue(r.Context(), "userClaims", claims)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}